<script setup>
import {useRoute, useRouter} from "vue-router";
import {ref} from 'vue';
import MyAxios from "../plugins/myAxios.ts";
import {showFailToast, showSuccessToast} from "vant";
import {getCurrentUser} from "../services/user.ts";

const route = useRoute()
const router = useRouter()
const editUser = ref({
  editKey: route.query.editKey,
  editName: route.query.editName,
  currentValue: route.query.currentValue
})

const onSubmit =  async () => {
  // 这里将 currentUser 写在函数里面是因为 如果写在外面会报错 async setup() is used without a suspense boundary
  // 需要在使用到 该组件的地方(父组件使用处)包裹 Suspense 组件(大概是因为异步操作未完成可能导致白屏)
  const currentUser = await getCurrentUser();
  if (!currentUser) {
    showFailToast('用户未登录');
    return;
  }
  console.log(currentUser.id)
  const res = await MyAxios.post('/user/update', {
    "id": currentUser.id,
    [editUser.value.editKey]: editUser.value.currentValue // 动态语法 动态生成 key
  });
  console.log(res, "更新请求");
  if (res.code === 0 && res.data > 0) {
    showSuccessToast('修改成功');
    router.back();
  } else {
    showFailToast('修改失败');
  }
};
</script>

<template>
  <van-form @submit="onSubmit">
      <van-field
          v-model="editUser.currentValue"
          :name="editUser.editKey"
          :label="editUser.editName"
          :placeholder="`请输入${editUser.editName}`"
          :rules="[{ required: true, message: `请输入${editUser.editName}`}]"
      />
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>

</template>

<style scoped>

</style>